﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Lenovo.CFI.BLL;
using Lenovo.CFI.Common.Dic;
using Lenovo.CFI.WebControls;
using Lenovo.CFI.Web.Helper;
using Lenovo.CFI.Common;
using Lenovo.CFI.BLL.Sys;
using Lenovo.CFI.BLL.DicMgr;

namespace Lenovo.CFI.Web.VP
{
    public partial class TopicSummary : System.Web.UI.UserControl
    {
        TopicBl topicBl = new TopicBl();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!IsPostBack)
                {
                    int? id = UrlHelper.GetQueryStringID();
                    Topic topic = null;
                    if (id.HasValue)
                    {
                        topic = topicBl.GetTopicByID(id.Value);
                    }
                    if (topic == null) ErrorHelper.RaiseNoValueError();

                    ViewState["topicid"] = topic.ID;

                    MessageHelper.Prepare(this.Page);

                    if (topic.Status == TopicStatus.Review)
                    {
                        this.UpSummary.Visible = false;

                        //评审结果
                        this.BindReviewStatus();
                    }
                    else if (topic.Status == TopicStatus.Summary)
                    {
                        this.DivStatus.Visible = false;

                        //汇总结果
                        this.BindSummary();
                    }
                    else
                        ErrorHelper.RaiseError("The specified topic can't be changed!");
                }
            }
        }

        //绑定评审结果，数量统计
        private void BindReviewStatus()
        {
            int topicID = Convert.ToInt32(ViewState["topicid"]);

            ReviewBl reviewBl = new ReviewBl();
            List<IdeaReviewDetail> details = reviewBl.GetReviewDetail(topicID, null);
            Dictionary<string, int[]> reviewerStatus = new Dictionary<string, int[]>();
            foreach (IdeaReviewDetail detail in details)
            {
                if (!reviewerStatus.ContainsKey(detail.Reviewer))
                    reviewerStatus.Add(detail.Reviewer, new int[2]);

                reviewerStatus[detail.Reviewer][0]++;
                if (detail.Finished) reviewerStatus[detail.Reviewer][1]++;
            }


            this.GvStatus.DataSource = reviewerStatus;
            this.GvStatus.DataBind();
        }

        protected void GvStatus_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);


                KeyValuePair<string, int[]> status = (KeyValuePair<string, int[]>)e.Row.DataItem;

                ((Literal)e.Row.FindControl("LtrReviewer")).Text = status.Key;

                LinkButton btnRemind = (LinkButton)e.Row.FindControl("BtnRemind");

                if (status.Value[0] == status.Value[1])
                {
                    ((Literal)e.Row.FindControl("LtrStatus")).Text = String.Format("Finished! ({0})", status.Value[0]);
                    btnRemind.Visible = false;
                }
                else
                {
                    ((Literal)e.Row.FindControl("LtrStatus")).Text = String.Format("({0})", status.Value[0]);
                    btnRemind.Visible = true;
                    btnRemind.CommandArgument = status.Key;
                }

            }
        }

        protected void GvStatus_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Remind")
            {
                try
                {
                    new ReviewBl().Remind(Convert.ToInt32(ViewState["topicid"]), e.CommandArgument.ToString());

                    MessageHelper.RegShowJSAjax(this.GvStatus, "Success!", this.Page);
                }
                catch (ApplicationException ex)
                {
                    MessageHelper.RegShowJSAjax(this.GvStatus, ex.Message, this.Page);
                }
            }
        }

        protected void BtnSummary_Click(object sender, EventArgs e)
        {
            try
            {
                topicBl.StartSummary(Convert.ToInt32(ViewState["topicid"]));

                MessageHelper.Show("Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.Show(ex.Message, this.Page);
            }

            this.DivStatus.Visible = false;
            this.UpSummary.Visible = true;

            this.BindSummary();
        }





        //绑定汇总结果
        Dictionary<int, Idea> ideasDic = null;
        private void BindSummary()
        {
            int topicID = Convert.ToInt32(ViewState["topicid"]);
            
            ReviewBl reviewBl = new ReviewBl();
            List<IdeaReview> ideaReviews = reviewBl.GetReview(topicID);
            Dictionary<int, IdeaReview> reviewsDic = new Dictionary<int, IdeaReview>();
            foreach (IdeaReview ideaReview in ideaReviews)
                reviewsDic.Add(ideaReview.ID, ideaReview);

            List<Idea> ideas = new IdeaBl().GetIdeaForReview(topicID);
            ideasDic = new Dictionary<int, Idea>();
            foreach (Idea idea in ideas) ideasDic.Add(idea.ID, idea);

            List<IdeaReviewDetail> details = reviewBl.GetReviewDetail(topicID, (string)ViewState["reviewer"]);
            foreach (IdeaReviewDetail detail in details)
                reviewsDic[detail.ReviewID].Details.Add(detail);

            this.GvIdeas.DataSource = ideaReviews;
            this.GvIdeas.DataBind();

            BindHelper.BindIdeaType(this.DdlReviewType, "Select...", "", "", false);

            this.GvReviewDetail.Visible = false;
            this.FsSummary.Visible = false;
            this.BtnSave.Visible = false;
        }


        protected void GvIdeas_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);


                IdeaReview review = (IdeaReview)e.Row.DataItem;
                Idea idea = ideasDic[review.IdeaID];

                ((Literal)e.Row.FindControl("LtrTitle")).Text = String.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                    UrlHelper.GenerateUrl("ideadetail", "id", idea.ID.ToString()), idea.Title);
                ((Literal)e.Row.FindControl("LtrOwner")).Text = idea.Owner;

                decimal cv = 0;
                decimal bv = 0;
                decimal tv = 0;
                if (review.Details.Count > 0)
                {
                    foreach (IdeaReviewDetail detail in review.Details)
                    {
                        cv += detail.Cv.Value;
                        bv += detail.Bv.Value;
                        tv += detail.Tv.Value;
                    }
                    cv = cv / review.Details.Count;
                    bv = bv / review.Details.Count;
                    tv = tv / review.Details.Count;
                }

                ((Literal)e.Row.FindControl("LtrCv")).Text = cv.ToString("f2");
                ((Literal)e.Row.FindControl("LtrBv")).Text = bv.ToString("f2");
                ((Literal)e.Row.FindControl("LtrTv")).Text = tv.ToString("f2");
            }
        }


        protected void GvIdeas_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Summary")
            {
                int reviewID = Convert.ToInt32(e.CommandArgument);
                ViewState["ReviewID"] = reviewID;

                ReviewBl reviewBl = new ReviewBl();

                IdeaReview review = reviewBl.GetReviewByID(reviewID);
                List<IdeaReviewDetail> details = reviewBl.GetReviewDetail(reviewID);

                decimal score = 0;
                if (details.Count > 0)
                {
                    details.ForEach(d=>score += (d.Cv.Value + d.Bv.Value + d.Tv.Value));
                    score = score / details.Count;
                }
                ViewState["Score"] = score;

                this.FsSummary.GroupingText = "Summary " + new IdeaBl().GetIdeaById(review.IdeaID).Title;

                this.DdlReviewType.ClearSelection();
                ListItem item = this.DdlReviewType.Items.FindByValue(review.ReviewType);
                if (item != null) item.Selected = true;

                this.DdlReviewIP.ClearSelection();
                item = this.DdlReviewIP.Items.FindByValue(review.ReviewIP == true ? "1" : "0");
                if (item != null) item.Selected = true;

                this.TxtRecord.Text = review.ReviewRecord.Format4Html();

                this.TxtSummary.Text = "";

                this.GvReviewDetail.Visible = true;
                this.FsSummary.Visible = true;
                this.BtnSave.Visible = true;


                this.GvReviewDetail.DataSource = details;
                this.GvReviewDetail.DataBind();
            }
        }

        protected void GvReviewDetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);

                IdeaReviewDetail detail = (IdeaReviewDetail)e.Row.DataItem;

                ((Literal)e.Row.FindControl("LtrReviewer")).Text = detail.Reviewer;
                ((Literal)e.Row.FindControl("LtrClass")).Text = String.IsNullOrEmpty(detail.Type) ? "" : IdeaTypeDicMgr.GetByCode(detail.Type).Title;
                ((Literal)e.Row.FindControl("LtrComment")).Text = detail.TypeComment.Format4Html();
                ((Literal)e.Row.FindControl("LtrSuggestion")).Text = String.IsNullOrEmpty(detail.Suggestion) ? "" : NextActionDicMgr.GetByCode(detail.Suggestion).Title;
                ((Literal)e.Row.FindControl("LtrIP")).Text = detail.Ip.HasValue ? (detail.Ip.Value ? "Y" : "N") : "";
                ((Literal)e.Row.FindControl("LtrIPComment")).Text = detail.IpComment.Format4Html();
            }
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            int reviewID = Convert.ToInt32(ViewState["ReviewID"]);

            ReviewBl reviewBl = new ReviewBl();

            try
            {
                reviewBl.Summary(reviewID, this.DdlReviewType.SelectedValue,
                    this.DdlReviewIP.SelectedIndex == 0,
                    this.TxtSummary.Text,
                    (decimal)ViewState["Score"]);

                MessageHelper.RegShowJSAjax(this.BtnSave, "success", this.Page);
            }
            catch (ApplicationException aex)
            {
                MessageHelper.RegShowJSAjax(this.BtnSave, aex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnSave, this.Page);
            }
        }

        

        //protected void BtnFinish_Click(object sender, EventArgs e)
        //{
        //    int topicID = Convert.ToInt32(ViewState["topicid"]);
        //}
    }
}